﻿using Ekton_Manage_DomainCore;
using Ekton_Manage_DomainCore.Aggregate;
using Ekton_Manage_Framework.Methods;
using Ekton_Manage_IBusiness;
using Ekton_Manage_InfrastructureCore.Common;
using Ekton_Manage_InfrastructureCore.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.Query;
using Ekton_Manage_InfrastructureCore.SqlSugarHelper;
using Ekton_Manage_DTO.RequestModels.Order;

namespace Ekton_Manage_Business
{
    public class OrderList : IOrderList
    {
        private readonly SerializeParameter _serialize;
        private readonly IBaseRepository<user_orderView, int> _baseuserOrderViewRepository;
        private readonly IBaseRepository<particulars_order, int> _baseparticularsOrderRepository;
        public OrderList(IBaseRepository<user_orderView, int> baseuserOrderViewRepository, SerializeParameter serialize, IBaseRepository<particulars_order, int> baseparticularsOrderRepository)
        {
            _baseuserOrderViewRepository = baseuserOrderViewRepository;
            _serialize = serialize;
            _baseparticularsOrderRepository = baseparticularsOrderRepository;
        }

        /// <summary>
        /// 查询订单的数量
        /// </summary>
        /// <param name="query"></param>
        /// <remarks>
        /// 1是近一周，2是近一个月，3是近一年
        /// </remarks>
        /// <returns></returns>
        public async Task<Message> GetOrderCount(int type)
        {
            var xAxis = new List<string>();
            var yAxis = new List<int>();
            switch (type)
            {
                case 1:
                    var date1 = DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-";
                    //非闰年的2月有28天
                    for (int i = 1; i <= 7; i++)
                    {
                        var dataList1 = await _baseuserOrderViewRepository.QueryTableList(m => m.order_time >= DateTime.Now.AddDays(-7) && m.order_time <= DateTime.Now);
                        var time = DateTime.Now.AddDays(-7 + i).ToShortDateString();
                        yAxis.Add(dataList1.Where(m => m.order_time >= Convert.ToDateTime(time) && m.order_time <= Convert.ToDateTime(time).AddDays(1)).Count().ObjToInt());
                    }
                    for (int i = 6; i >= 0; i--)
                    {
                        //x轴坐标
                        xAxis.Add(DateTime.Now.AddDays(-i).ToString("yyyy-MM-dd"));
                        //y轴销量
                    };
                    var res1 = new
                    {
                        xAxis = xAxis,
                        yAxis = yAxis
                    };
                    return new Message(res1);
                case 2:
                    var dataList2 = await _baseuserOrderViewRepository.QueryTableList(m => m.order_time >= DateTime.Now.AddDays(-30) && m.order_time <= DateTime.Now);
                    //近一个月
                    for (int i = 30; i >= 0; i--)
                    {
                        //x轴坐标
                        xAxis.Add(DateTime.Now.AddDays(-i).ToString("yyyy-MM-dd"));
                    };

                    for (int i = 0; i <= 30; i++)
                    {                        
                        //y轴销量
                        var time = DateTime.Now.AddDays(-30 + i).ToShortDateString();
                        yAxis.Add(dataList2.Where(m => m.order_time >= Convert.ToDateTime(time) && m.order_time <= Convert.ToDateTime(time).AddDays(1)).Count().ObjToInt());
                    }
                    var res2 = new
                    {
                        xAxis = xAxis,
                        yAxis = yAxis
                    };
                    return new Message(res2);
                case 3:
                    var dataList3 = await _baseuserOrderViewRepository.QueryTableList(m => m.order_time >= DateTime.Now.AddYears(-1) && m.order_time <= DateTime.Now);
                    var date3 = DateTime.Now.Year.ToString() + "-";
                    //近一年
                    for (int i = 11; i >= 0; i--)
                    {
                        //x轴坐标
                        xAxis.Add(DateTime.Now.AddMonths(-i).ToString("yyyy-MM"));
                        //y轴销量
                    };
                    for (int i = 0; i < 12; i++)
                    {
                        var s = DateTime.Now.AddMonths(-11 + i).Month;
                        if (s > DateTime.Now.Month)
                        {
                            var date4 = DateTime.Now.AddYears(-1).Year.ToString() + "-";
                            yAxis.Add(dataList3.Where(m => m.order_time >= Convert.ToDateTime(date4 + s) && m.order_time <= Convert.ToDateTime(date4 + s).AddMonths(1)).Count().ObjToInt());
                        }
                        else
                        {
                            yAxis.Add(dataList3.Where(m => m.order_time >= Convert.ToDateTime(date3 + s) && m.order_time <= Convert.ToDateTime(date3 + s).AddMonths(1)).Count().ObjToInt());
                        }

                    }
                    var res3 = new
                    {
                        xAxis = xAxis,
                        yAxis = yAxis
                    };
                    return new Message(res3);
                default:
                    break;
            }
            return null;
        }

        /// <summary>
        ///  查询全部订单
        /// </summary>
        /// 
        public async Task<Tuple<List<user_orderView>, int>> SelectOrderList(QueryDataParame query)
        {
            var orderInfo = await _serialize.ParameConvertToDict(query.parame);
            Expression<Func<user_orderView, bool>> expression = m => true;
            if (orderInfo.ContainsKey("order_id") && !string.IsNullOrEmpty(orderInfo["order_id"].ToString()))
            {
                expression = expression.ExpressionAnd(m => m.order_id.Contains(orderInfo["order_id"].ToString()));
            }
            if (orderInfo.ContainsKey("name") && !string.IsNullOrEmpty(orderInfo["name"].ToString()))
            {
                expression = expression.ExpressionAnd(m => m.name.Contains(orderInfo["name"].ToString()));
            }
            if (orderInfo.ContainsKey("company") && !string.IsNullOrEmpty(orderInfo["company"].ToString()))
            {
                expression = expression.ExpressionAnd(m => m.company.Contains(orderInfo["company"].ToString()));
            }
            if (orderInfo.ContainsKey("state") && !string.IsNullOrEmpty(orderInfo["state"].ToString()))
            {
                expression = expression.ExpressionAnd(m => m.state == orderInfo["state"].ObjToInt());
            }
            if (orderInfo.ContainsKey("order_time") && !string.IsNullOrEmpty(orderInfo["order_time"].ToString()))
            {
                expression = expression.ExpressionAnd(m => m.order_time >= orderInfo["order_time"].ObjToDate() && m.create_op_date <= orderInfo["order_time"].ObjToDate().AddDays(1));
            }
            return await _baseuserOrderViewRepository.QueryPageData(query, expression);
        }

        /// <summary>
        /// 订单量
        /// </summary>
        public async Task<Message> GetOrderNumber()
        {
            //本月订单量
            var year = DateTime.Now.Year.ToString();
            var month = DateTime.Now.Month.ToString();
            var day = 1;
            var time = year + "-" + month + "-" + day;
            var monthRes = await _baseuserOrderViewRepository.QueryCount(m => m.order_time >= time.ObjToDate() && m.order_time <= time.ObjToDate().AddMonths(1));
            //今日订单量
            var today = DateTime.Now.ToString("yyyy-MM-dd");
            var todayRes = await _baseuserOrderViewRepository.QueryCount(m => m.order_time >= today.ObjToDate() && m.order_time <= today.ObjToDate().AddDays(1));
            //总订单量
            var total = await _baseuserOrderViewRepository.QueryCount(m => true);
            var res = new
            {
                monthOrderNum = monthRes,
                todayOrderNum = todayRes,
                orderTotal = total
            };
            return new Message(res);
        }

        /// <summary>
        /// 修改订单状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public async Task<Message> PutOrderState(int id, int state)
        {
            var res = await _baseparticularsOrderRepository.QuerySingleData(id);
            if (res == null) return new Message(false, 202);
            res.state = state;
            var result = await _baseparticularsOrderRepository.UpdateSingleData(res);
            return new Message(result);
        }
    }
}
